<template>
  <div class="modal-overlay" @click.self="$emit('close')">
    <div class="modal-container">
      <div class="modal-header">
        <div class="modal-title">{{ isLogin ? t('welcome_login') : t('register_account') }}</div>
        <div class="modal-subtitle">{{ t('home_title') }}</div>
        <div class="close-btn" @click="$emit('close')">×</div>
      </div>
      
      <div class="modal-content">
        <!-- 登录/注册切换 -->
        <div class="auth-tabs">
          <div 
            class="tab-item" 
            :class="{ 'active': isLogin }"
            @click="switchToLogin"
          >
            {{ t('account_login') }}
          </div>
          <div 
            class="tab-item" 
            :class="{ 'active': !isLogin }"
            @click="switchToRegister"
          >
            {{ t('register_account') }}
          </div>
        </div>

        <!-- 登录表单 -->
        <div v-if="isLogin" class="auth-form">
          <!-- 登录方式切换 -->
          <div class="login-type-tabs">
            <div 
              class="type-tab" 
              :class="{ 'active': loginType === 'password' }"
              @click="loginType = 'password'"
            >
              {{ t('password_login') }}
            </div>
            <div 
              class="type-tab" 
              :class="{ 'active': loginType === 'code' }"
              @click="loginType = 'code'"
            >
              {{ t('captcha_login') }}
            </div>
          </div>

          <!-- 手机号输入 -->
          <div class="form-group">
            <label>{{ t('email_phone') }}</label>
            <input 
              v-model="loginForm.phone" 
              type="text" 
              :placeholder="t('please_input_email_phone')"
              class="form-input"
              :maxlength="30"
            />
          </div>

          <!-- 密码登录 -->
          <div v-if="loginType === 'password'" class="form-group">
            <label>{{ t('password') }}</label>
            <div class="password-input-container">
              <input 
                v-model="loginForm.password" 
                :type="showPassword ? 'text' : 'password'" 
                :placeholder="t('please_input_password')"
                class="form-input"
              />
              <span class="toggle-password" @click="showPassword = !showPassword">
                <i :class="showPassword ? 'el-icon-view' : 'el-icon-view-off'"></i>
              </span>
            </div>
            <div class="forgot-password" @click="handleForgotPassword">
              {{ t('forget_password') }}
            </div>
          </div>

          <!-- 验证码登录 -->
          <div v-else class="form-group">
            <label>{{ t('code') }}</label>
            <div class="verification-code-container">
              <input 
                v-model="loginForm.code" 
                type="text" 
                :placeholder="t('please_input_code')"
                class="form-input verification-code-input"
                maxlength="6"
              />
              <button 
                class="verification-code-btn" 
                @click="sendVerificationCode('login')"
                :disabled="(!isPhoneValid(loginForm.phone) && !isEmailValid(loginForm.phone)) || loginCooldown > 0"
                :class="{ 'cooldown': loginCooldown > 0 }"
              >
                {{ loginCooldown > 0 ? `${loginCooldown}${t('wait_time')}` : t('get_code') }}
              </button>
            </div>
          </div>

          <div class="form-actions">
            <button 
              class="submit-btn" 
              @click="handleLogin"
              :disabled="!isLoginFormValid || loading"
              :class="{ 'loading': loading }"
            >
              {{ t('login') }}
            </button>
            
            <!-- 分割线 -->
            <div class="divider">
              <span class="divider-text">{{ t('other_login_way') }}</span>
            </div>
            
            <!-- 第三方登录 -->
            <div class="third-party-login">
              <button class="wx-login-btn" @click="handleWechatLogin" :title="t('wechat_login')">
                <i class="wx-icon"></i>
                <span>{{ t('wechat_login') }}</span>
              </button>
            </div>
          </div>
        </div>

        <!-- 注册表单 -->
        <div v-else class="auth-form">
          <div class="form-group">
            <label>{{ t('email_phone') }}</label>
            <input 
              v-model="registerForm.account" 
              type="text" 
              :placeholder="t('please_input_email_phone')"
              class="form-input"
            />
          </div>

          <div class="form-group">
            <label>{{ t('code') }}</label>
            <div class="verification-code-container">
              <input 
                v-model="registerForm.code" 
                type="text" 
                :placeholder="t('please_input_code')"
                class="form-input verification-code-input"
                maxlength="6"
              />
              <button 
                class="verification-code-btn" 
                @click="sendVerificationCode('register')"
                :disabled="!registerForm.account || registerCooldown > 0"
                :class="{ 'cooldown': registerCooldown > 0 }"
              >
                {{ registerCooldown > 0 ? `${registerCooldown}${t('wait_time')}` : t('get_code') }}
              </button>
            </div>
          </div>

          <div class="form-group">
            <label>{{ t('set_password') }}</label>
            <div class="password-input-container">
              <input 
                v-model="registerForm.password" 
                :type="showRegisterPassword ? 'text' : 'password'" 
                :placeholder="t('please_set_password')"
                class="form-input"
              />
              <span class="toggle-password" @click="showRegisterPassword = !showRegisterPassword">
                <i :class="showRegisterPassword ? 'el-icon-view' : 'el-icon-view-off'"></i>
              </span>
            </div>
          </div>

          <div class="form-group">
            <label>{{ t('confirm_password') }}</label>
            <div class="password-input-container">
              <input 
                v-model="registerForm.confirmPassword" 
                :type="showConfirmPassword ? 'text' : 'password'" 
                :placeholder="t('please_confirm_password')"
                class="form-input"
              />
              <span class="toggle-password" @click="showConfirmPassword = !showConfirmPassword">
                <i :class="showConfirmPassword ? 'el-icon-view' : 'el-icon-view-off'"></i>
              </span>
            </div>
          </div>

          <div class="form-actions">
            <button 
              class="submit-btn" 
              @click="handleRegister"
              :disabled="!isRegisterFormValid || loading"
              :class="{ 'loading': loading }"
            >
              {{ t('register') }}
            </button>
          </div>
        </div>

        <!-- 用户协议 -->
        <div class="agreement">
          {{ t('register_agree') }}
          <a href="#" class="agreement-link">《{{ t('user_agreement') }}》</a> {{t('and')}}
          <a href="#" class="agreement-link">《{{ t('privacy_policy') }}》</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineEmits, onBeforeUnmount, onMounted } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { login, register, sendSmsCode, saveUserInfo, getWechatLoginUrl, checkWechatLoginStatus } from '@/api/login'
import { useUserStore } from '@/store/userStore'
import { useLanguageStore } from '@/store/languageStore'
const { t } = useLanguageStore();
const userStore = useUserStore();

const emit = defineEmits(['close', 'login-success'])

// 登录相关状态
const isLogin = ref(true)
const loginType = ref('password') // 'password' 或 'code'
const showPassword = ref(false)
const showRegisterPassword = ref(false)
const showConfirmPassword = ref(false)
const loading = ref(false)

// 登录表单
const loginForm = ref({
  phone: '',
  password: '',
  code: ''
})
const isSendingCode = ref(false)
// 注册表单
const registerForm = ref({
  account: '',
  code: '',
  password: '',
  confirmPassword: ''
})

// 验证码倒计时
const loginCooldown = ref(0)
const registerCooldown = ref(0)
let loginTimer = null
let registerTimer = null

// 切换登录/注册
const switchToLogin = () => {
  isLogin.value = true
  resetForms()
}

const switchToRegister = () => {
  isLogin.value = false
  resetForms()
}

const resetForms = () => {
  // 重置登录表单
  loginForm.value = {
    phone: '',
    password: '',
    code: ''
  }
  // 重置注册表单
  registerForm.value = {
    account: '',
    code: '',
    password: '',
    confirmPassword: ''
  }
  // 重置状态
  showPassword.value = false
  showRegisterPassword.value = false
  showConfirmPassword.value = false
}

// 验证手机号格式
const isPhoneValid = (phone) => {
  return /^1[3-9]\d{9}$/.test(phone)
}

// 验证邮箱格式
const isEmailValid = (email) => {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
}

// 登录表单验证
const isLoginFormValid = computed(() => {
  if (loginType.value === 'password') {
    const isAccountValid = isPhoneValid(loginForm.value.phone) || isEmailValid(loginForm.value.phone)
    return isAccountValid && loginForm.value.password.length >= 6
  } else {
    return (isPhoneValid(loginForm.value.phone) || isEmailValid(loginForm.value.phone)) && loginForm.value.code.length === 6
  }
})

// 注册表单验证
const isRegisterFormValid = computed(() => {
  const { account, code, password, confirmPassword } = registerForm.value
  const isAccountValid = isPhoneValid(account) || isEmailValid(account)
  return isAccountValid && 
         code.length === 6 && 
         password.length >= 6 && 
         password === confirmPassword
})

// 发送验证码
const sendVerificationCode = async (type) => {
  // 如果正在发送中，则不重复触发
  if (isSendingCode.value) {
    ElMessage.info(t('please_dont_operate_frequently'));
    return;
  }
  
  // 设置发送状态为true
  isSendingCode.value = true;
  
  // 登录验证码
  if (type === 'login') {
    if (!isPhoneValid(loginForm.value.phone) && !isEmailValid(loginForm.value.phone)) {
      ElMessage.error(t('please_input_email_phone'))
      return
    }
    
    // 调用发送验证码接口
    try {
      const res = await sendSmsCode({
        phone: loginForm.value.phone,
        type: 'login'
      })
      
      if (res.code === 0) {
        startCooldown('login')
        ElMessage.success(t('verification_code_sent_successfully'))
      } else {
        ElMessage.error(t(res.msg) || t('verification_code_send_failed'))
      }
    } catch (error) {
      ElMessage.error(error.message || t('verification_code_send_failed'))
    } finally {
      // 无论成功失败，都重置发送状态
      isSendingCode.value = false;
    }
  } 
  // 注册验证码
  else if (type === 'register') {
    const { account } = registerForm.value
    if (!isPhoneValid(account) && !isEmailValid(account)) {
      ElMessage.error(t('please_input_email_phone'))
      return
    }
    
    // 调用发送验证码接口
    try {
      const res = await sendSmsCode({
        phone: account,
        type: 'register'
      })
      
      if (res.code === 0) {
        startCooldown('register')
        ElMessage.success(t('verification_code_sent_successfully'))
      } else {
        ElMessage.error(t('verification_code_send_failed'))
      }
    } catch (error) {
      ElMessage.error(t('verification_code_send_failed'))
    } finally {
      // 无论成功失败，都重置发送状态
      isSendingCode.value = false;
    }
  }
}

// 开始倒计时
const startCooldown = (type) => {
  if (type === 'login') {
    loginCooldown.value = 60
    loginTimer = setInterval(() => {
      loginCooldown.value--
      if (loginCooldown.value <= 0) {
        clearInterval(loginTimer)
      }
    }, 1000)
  } else if (type === 'register') {
    registerCooldown.value = 60
    registerTimer = setInterval(() => {
      registerCooldown.value--
      if (registerCooldown.value <= 0) {
        clearInterval(registerTimer)
      }
    }, 1000)
  }
}

// 处理登录
const handleLogin = async () => {
  if (!isLoginFormValid.value || loading.value) return
  
  try {
    loading.value = true
    
    // 构建登录参数
    const loginData = {
      phone: loginForm.value.phone,
      login_type: loginType.value
    }
    
    // 根据登录类型添加密码或验证码
    if (loginType.value === 'password') {
      loginData.password = loginForm.value.password
    } else {
      loginData.code = loginForm.value.code
    }
    
    // 调用登录API
    const res = await login(loginData)
    
    if (res.code === 0) {
      // 保存用户信息和令牌
      saveUserInfo(res.data.user, res.data.token)
      
      ElMessage.success(t('login_success'))
      userStore.login(res.data.user)
      emit('login-success', res.data.user)
      emit('close')
    } else {
      ElMessage.error(t(res.msg) || t('login_failed'))
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.message || t('login_failed'))
  } finally {
    loading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  if (!isRegisterFormValid.value || loading.value) return
  
  const { account, code, password } = registerForm.value
  
  try {
    loading.value = true
    
    // 构建注册参数
    const registerData = {
      account,
      code,
      password
    }
    
    // 调用注册API
    const res = await register(registerData)
    
    if (res.code === 0) {
      ElMessage.success(t('register_success'))
      switchToLogin()
    } else {
      ElMessage.error(t(res.msg) || t('register_failed'))
    }
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error(error.message || t('register_failed'))
  } finally {
    loading.value = false
  }
}

// 忘记密码
const handleForgotPassword = () => {
  ElMessage.info(t('forgot_password'))
  loginType.value = 'code'
}

// 微信登录状态轮询定时器
let wechatLoginTimer = null

// 检测是否是微信内置浏览器
const isWechatBrowser = () => {
  const ua = navigator.userAgent.toLowerCase()
  return /micromessenger/i.test(ua)
}

// 检测是否是移动设备
const isMobileDevice = () => {
  const ua = navigator.userAgent.toLowerCase()
  return /mobile|android|iphone|ipod|ipad/i.test(ua)
}

// 微信登录
const handleWechatLogin = async () => {
  try {
    loading.value = true
    // 清除可能存在的旧state，确保每次登录都获取新的state
    localStorage.removeItem('wechat_login_state')
    sessionStorage.removeItem('wechat_login_state')
    
    // 检查用户环境
    const isInWechat = isWechatBrowser()
    const isOnMobile = isMobileDevice()
    
    console.log('微信登录环境检测:', { isInWechat, isOnMobile })
    
    // 获取微信登录链接，传递设备类型信息
    const res = await getWechatLoginUrl(isInWechat, isOnMobile)
    
    if (res.code === 0 && res.data.url) {
      // 从链接中提取state参数，用于后续查询登录状态
      const urlObj = new URL(res.data.url)
      const state = urlObj.searchParams.get('state')
      
      if (!state) {
        ElMessage.error('获取微信授权参数失败')
        return
      }
      
      console.log('微信登录state:', state)
      
      // 将state同时存储到localStorage和sessionStorage，双重保险
      localStorage.setItem('wechat_login_state', state)
      sessionStorage.setItem('wechat_login_state', state)
      
      // 区分处理：微信内置浏览器必须跳转，其他可以使用轮询
      if (isInWechat && isOnMobile) {
        // 微信内置浏览器：必须使用页面跳转（因为无法打开新窗口）
        console.log('移动端微信浏览器，使用页面跳转方式')
        
        // 保存当前页面信息，用于返回后恢复
        sessionStorage.setItem('wechat_login_pending', 'true')
        sessionStorage.setItem('wechat_login_time', Date.now().toString())
        
        // 直接跳转到授权页面
        window.location.href = res.data.url
      } 
      // PC端或非微信移动浏览器：使用弹窗 + 轮询方式
      else {
        console.log('使用弹窗轮询方式')
        const authWindow = window.open(res.data.url, '_blank', 'width=800,height=600')
        
        if (!authWindow || authWindow.closed) {
          ElMessage.error('无法打开授权窗口，请检查浏览器设置')
          return
        }
        
        // 开始轮询检查登录状态
        startWechatLoginCheck(state, authWindow, false)
      }
    } else {
      ElMessage.error(t(res.msg) || t('get_wechat_login_link_failed'))
    }
  } catch (error) {
    console.error('微信登录失败:', error)
    ElMessage.error(error.message || t('get_wechat_login_link_failed'))
  } finally {
    loading.value = false
  }
}

// 开始微信登录状态轮询检查
// 增加isMobileFlow参数标识是否为移动端流程
const startWechatLoginCheck = (state, authWindow, isMobileFlow = false) => {
  console.log('开始微信登录状态检查:', { state, isMobileFlow })
  
  // 清除可能存在的旧定时器
  if (wechatLoginTimer) {
    clearInterval(wechatLoginTimer)
  }
  
  // 设置检查次数和间隔
  let checkCount = 0
  const maxChecks = 90 // 最多检查90次（约3分钟）
  let retryCount = 0
  const maxRetries = 3 // 最多重试3次
  let consecutiveErrors = 0 // 连续错误次数
  
  // 移动端首次检查延迟500ms，给后端足够时间设置缓存
  const firstCheckDelay = isMobileFlow ? 500 : 0
  
  setTimeout(() => {
    // 创建轮询定时器，每2秒检查一次登录状态
    wechatLoginTimer = setInterval(async () => {
      try {
        // 检查次数增加
        checkCount++
        console.log(`微信登录检查第 ${checkCount} 次, state: ${state}`)
        
        // 如果是PC端流程，检查窗口是否关闭
        if (!isMobileFlow && authWindow && authWindow.closed) {
          console.log('PC端授权窗口已关闭，停止检查')
          clearInterval(wechatLoginTimer)
          return
        }
        
        // 如果超过最大检查次数，停止轮询
        if (checkCount > maxChecks) {
          console.log('微信登录检查超时')
          clearInterval(wechatLoginTimer)
          ElMessage.info(t('wechat_login_timeout'))
          return
        }
        
        // 调用接口检查登录状态
        const result = await checkWechatLoginStatus(state)
        console.log(`微信登录状态检查结果:`, result)
        
        // 重置连续错误计数
        consecutiveErrors = 0
        
        // 如果登录成功
        if (result.code === 0 && result.data && result.data.token) {
          console.log('微信登录成功！')
          clearInterval(wechatLoginTimer)
          
          // 关闭Loading提示
          ElMessage.closeAll()
          
          // 处理登录成功，保存用户信息和token
          saveUserInfo(result.data.user, result.data.token)
          
          // 使用更友好的通知展示用户信息
          const nickname = result.data.user?.nickname || '用户'
          
          // 如果是PC端流程且窗口存在，关闭授权窗口
          if (!isMobileFlow && authWindow && !authWindow.closed) {
            authWindow.close()
          }
          
          // 使用更友好的通知展示用户信息
          ElNotification({
            title: t('login_success'),
            message: `${t('welcome_back')},${nickname}！`,
            type: 'success',
            duration: 3000
          })
          
          // 清理存储的state
          localStorage.removeItem('wechat_login_state')
          sessionStorage.removeItem('wechat_login_state')
          sessionStorage.removeItem('wechat_login_time')
          sessionStorage.removeItem('wechat_login_pending')
          
          // 触发登录成功事件并关闭弹窗
          emit('login-success', result.data.user)
          emit('close')
          
          // 移动端微信浏览器：延迟刷新页面以更新用户状态
          // 先让用户看到成功通知，然后再刷新
          if (isMobileFlow) {
            setTimeout(() => {
              window.location.reload()
            }, 1500) // 1.5秒后刷新，让用户看到成功提示
          }
        } 
        // 如果登录失败
        else if (result.code !== 2) { // code=2表示等待登录中
          console.log('微信登录失败:', result.msg)
          clearInterval(wechatLoginTimer)
          
          // 关闭Loading提示
          ElMessage.closeAll()
          
          ElNotification({
            title: t('login_failed'),
            message: result.msg || t('login_failed'),
            type: 'error',
            duration: 4000
          })
          
          // 清理存储的state
          localStorage.removeItem('wechat_login_state')
          sessionStorage.removeItem('wechat_login_state')
        } else {
          console.log(`等待微信授权登录... (${checkCount}/${maxChecks})`)
        }
      } catch (error) {
        console.error('检查微信登录状态失败:', error)
        retryCount++
        consecutiveErrors++
        
        // 如果连续错误超过5次，可能是网络问题
        if (consecutiveErrors >= 5) {
          clearInterval(wechatLoginTimer)
          
          // 关闭Loading提示
          ElMessage.closeAll()
          
          ElMessage.error('网络连接异常，请检查网络后重试')
          return
        }
        
        // 如果重试次数超过限制，停止轮询
        if (retryCount >= maxRetries) {
          clearInterval(wechatLoginTimer)
          ElMessage.error('网络异常，请重试微信登录')
          return
        }
        
        // 否则继续轮询，但记录错误
        console.log(`微信登录检查失败，将重试 (${retryCount}/${maxRetries})`)
      }
    }, 2000) // 每2秒检查一次
  }, firstCheckDelay)
}

// 组件挂载时检测是否从微信授权返回
onMounted(() => {
  console.log('LoginModal组件已挂载')
  
  // 检测是否在微信内置浏览器中
  const isInWechat = isWechatBrowser()
  const isOnMobile = isMobileDevice()
  
  // 检查是否有待处理的微信登录
  const isPending = sessionStorage.getItem('wechat_login_pending')
  const loginTime = sessionStorage.getItem('wechat_login_time')
  const wechatState = sessionStorage.getItem('wechat_login_state') || localStorage.getItem('wechat_login_state')
  
  console.log('微信登录状态检测:', { isPending, loginTime, wechatState, isInWechat, isOnMobile })
  
  // 如果是从微信授权返回（5分钟内）
  if (isPending && loginTime && wechatState) {
    const timeDiff = Date.now() - parseInt(loginTime)
    if (timeDiff < 5 * 60 * 1000) { // 5分钟内有效
      console.log('检测到微信授权返回，开始轮询检查登录状态')
      
      // 显示Loading提示，让用户知道正在处理
      ElMessage({
        message: '正在完成登录，请稍候...',
        type: 'info',
        duration: 0, // 不自动关闭
        customClass: 'wechat-login-loading'
      })
      
      // 【重要】不要立即清除pending标记，等登录成功后再清除
      // 这样可以确保MainLayout能检测到pending并自动打开LoginModal
      
      // 标记为移动端流程
      const isMobileFlow = isInWechat && isOnMobile
      
      // 立即开始轮询检查
      startWechatLoginCheck(wechatState, null, isMobileFlow)
      
      return
    } else {
      // 超时，清理过期数据
      console.log('微信登录已超时，清理过期数据')
      sessionStorage.removeItem('wechat_login_pending')
      sessionStorage.removeItem('wechat_login_time')
      localStorage.removeItem('wechat_login_state')
      sessionStorage.removeItem('wechat_login_state')
    }
  }
  
  // 清理可能残留的旧state（延迟清理，避免影响正在进行的登录）
  setTimeout(() => {
    const hasState = localStorage.getItem('wechat_login_state') || sessionStorage.getItem('wechat_login_state')
    if (hasState && !isPending) {
      console.log('清理残留的微信登录state')
      localStorage.removeItem('wechat_login_state')
      sessionStorage.removeItem('wechat_login_state')
    }
  }, 30000) // 30秒后清理
})

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (loginTimer) clearInterval(loginTimer)
  if (registerTimer) clearInterval(registerTimer)
  if (wechatLoginTimer) clearInterval(wechatLoginTimer)
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.modal-container {
  background-color: #2d2d30;
  border-radius: 12px;
  width: 90%;
  max-width: 400px;
  overflow: hidden;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
  position: relative;
}

.modal-header {
  background: linear-gradient(135deg, #1a365d 0%, #0078FF 100%);
  padding: 20px;
  text-align: center;
  color: white;
  position: relative;
}

.modal-title {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 5px;
}

.modal-subtitle {
  font-size: 14px;
  opacity: 0.9;
}

.modal-content {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #e0e0e0;
  font-size: 14px;
}

.form-input {
  width: 100%;
  padding: 10px 12px;
  border-radius: 6px;
  border: 1px solid #444;
  background-color: #252526;
  color: #fff;
  font-size: 14px;
}

.form-input:focus {
  outline: none;
  border-color: #4dabf7;
}

.verification-code-container {
  display: flex;
  gap: 10px;
}

.verification-code-input {
  flex: 1;
}

.verification-code-btn {
  min-width: 100px;
  background-color: #4dabf7;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 0 12px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
}

.verification-code-btn:hover:not(:disabled) {
  background-color: #3b92c7;
}

.verification-code-btn:disabled {
  background-color: #444;
  cursor: not-allowed;
  color: #999;
}

.verification-code-btn.cooldown {
  background-color: #444;
  color: #999;
}

.forgot-password {
  text-align: right;
  margin-top: 8px;
  font-size: 12px;
  color: #999;
  cursor: pointer;
  transition: color 0.2s;
}

.forgot-password:hover {
  color: #4dabf7;
}

.form-actions {
  margin-top: 24px;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background-color: #4dabf7;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.submit-btn:hover:not(:disabled) {
  background-color: #3b92c7;
}

.submit-btn:disabled {
  background-color: #444;
  cursor: not-allowed;
  color: #999;
}

.submit-btn.loading {
  position: relative;
  color: transparent !important;
  pointer-events: none;
}

.submit-btn.loading::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 20px;
  height: 20px;
  margin: -10px 0 0 -10px;
  border: 2px solid #fff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.close-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  font-size: 24px;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

/* 登录/注册标签页 */
.auth-tabs {
  display: flex;
  margin-bottom: 24px;
  border-bottom: 1px solid #444;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  cursor: pointer;
  color: #999;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s;
  position: relative;
}

.tab-item.active {
  color: #4dabf7;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 2px;
  background-color: #4dabf7;
}

/* 登录方式标签 */
.login-type-tabs {
  display: flex;
  margin-bottom: 20px;
  background-color: #252526;
  border-radius: 6px;
  padding: 4px;
}

.type-tab {
  flex: 1;
  text-align: center;
  padding: 8px 0;
  cursor: pointer;
  color: #999;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.3s;
}

.type-tab.active {
  background-color: #2d2d30;
  color: #4dabf7;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 密码输入框容器 */
.password-input-container {
  position: relative;
}

.toggle-password {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  cursor: pointer;
  font-size: 16px;
}

.toggle-password:hover {
  color: #4dabf7;
}

/* 分割线 */
.divider {
  display: flex;
  align-items: center;
  margin: 24px 0;
  color: #666;
  font-size: 12px;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background-color: #444;
}

.divider-text {
  padding: 0 12px;
}

/* 第三方登录 */
.third-party-login {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.wx-login-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2aae67;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.wx-login-btn:hover {
  background-color: #249d5c;
}

.wx-icon {
  display: inline-block;
  width: 20px;
  height: 20px;
  background-image: url('');
  background-size: cover;
  margin-right: 8px;
}

/* 用户协议 */
.agreement {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-top: 20px;
}

.agreement-link {
  color: #4dabf7;
  text-decoration: none;
}

.agreement-link:hover {
  text-decoration: underline;
}
</style>